package com.gym.controller.action.customer;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.gym.controller.form.FormLogin;
import com.gym.model.dao.ConnessioneException;
import com.gym.model.dao.DAOCustomer;
import com.gym.model.dao.DAOUser;
import com.gym.model.dao.DatoNonTrovatoException;
import com.gym.model.dao.MetodoDaoException;
import com.gym.model.entity.User;

public class ActionLogin extends Action {

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form, 
			HttpServletRequest request, HttpServletResponse response) {
		
		FormLogin f = (FormLogin)form;
		
		try {
			DAOUser daoUser = new DAOUser();
			DAOCustomer daoCustomer = new DAOCustomer();
			
			String email = f.getEmail();
			String password = crittografia(f.getPassword());
			
			User user = daoUser.selectByEmail(email);

			if(user != null && user.getPassword().equals(password)) {
				request.getSession().setAttribute("user", daoUser.selectByEmail(email));
				request.getSession().setAttribute("customer", daoCustomer.selectByUser(user));
				
				if(user.isCustomer())		
					return mapping.findForward("success");
				else
					return mapping.findForward("successAdmin");
			} 
			
			request.setAttribute("error", (user==null ? "Utente non trovato" : "Password errata") );
			return mapping.findForward("failure");

		} catch (ConnessioneException | MetodoDaoException | DatoNonTrovatoException | NoSuchAlgorithmException e) {
			request.setAttribute("error", e.getMessage());
			return mapping.findForward("failure");
		}
	}
	
	
	private String crittografia(String password) throws NoSuchAlgorithmException {  {
		MessageDigest mDigest = MessageDigest.getInstance("SHA1");
		byte[] result = mDigest.digest(password.getBytes());
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < result.length; i++) {
			sb.append(Integer.toString((result[i] & 0xff) + 0x100, 16).substring(1));
		}

		return sb.toString();
	}
}

}
